<template>
  <el-dialog
    v-if="setEdit"
    v-el-drag-dialog="{resize: resize, updataFull, updataDialogWidth}"
    v-loading="loading"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('1200px')"
    :visible="visible"
    :title="$t('MODIFY_CHANNEL_STATUS')"
    :append-to-body="true"
    class="segment-dialog"
    @close="close"
  >
    <step-two
      v-show="step === 2"
      ref="StepTwo"
      :form-data="formData"
      :type="type"
      :step="step"
      :old-channel-list="oldChannelList"
    />
    <template v-slot:footer>
      <el-button @click="close">{{
        $t('CANCEL')
      }}</el-button>
      <el-button
        type="primary"
        @click="$debounce(save)"
      >{{ $t('SAVE') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import segmentChannelApi from '@/api/oen/SegmentChannelApi'
  import { deepClone } from '@/utils/common'
  import StepTwo from './components/StepTwo.vue'

  export default {
    components: { StepTwo },
    props: {
      setEdit: {
        type: Boolean,
        default: true
      },
      visible: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: ''
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        loading: false,
        step: 1,
        formData: {
          segmentName: '',
          startStationId: null,
          startNodeId: '',
          endStationId: null,
          endNodeId: '',
          cable: {
            cableName: ''
          },
          cableId: null,
          cableLength: '',
          startNode: {
            nodeName: ''
          },
          endNode: {
            nodeName: ''
          },
          segmentChannelList: [
            {
              startPortId: '',
              fiberId: '',
              endPortId: ''
            }
          ]
        },
        oldChannelList: [],
        oldFormData: null
      }
    },
    computed: {
      ...mapGetters(['dictList'])
    },
    methods: {
      open() {
        this.oldChannelList = []
        this.oldFormData = null
        this.loading = true
        this.step = 2
        segmentChannelApi
          .queryOne({
            segmentId: this.rowData.segmentId
          })
          .then((res) => {
            const segmentChannelList = res || []
            segmentChannelList.forEach((i) => {
              this.loading = false
              i.startPort = i.startPort || {}
              i.endPort = i.endPort || {}
              i.startPort.bizName = this.$utils.handleServiceI18n(
                i.startPort.bizName
              )
              i.endPort.bizName = this.$utils.handleServiceI18n(
                i.endPort.bizName
              )
              i.statusOptions = this.getStatusOptions(i.status)
            })
            this.oldChannelList = deepClone(segmentChannelList)
            this.rowData.segmentChannelList = segmentChannelList
            this.callStepTwo()
          })
      },
      /**
       * 获取通道可选择的状态（主用、备用、处理中、损坏、空闲）
       * 变更前是非主用或非备用、非处理中，可以改成损坏（就是空闲的可以变成损坏）
       * 损坏的可以变成空闲
       */
      getStatusOptions(status) {
        return this.dictList.CHANNEL_STATUS.filter(
          (i) =>
            (status === 'DAMAGE' && i.value === 'IDLE') ||
            i.value === status ||
            (status === 'IDLE' && i.value === 'DAMAGE')
        )
      },
      // 跳转第二步
      callStepTwo() {
        this.formData = this.rowData.id
          ? deepClone(this.rowData)
          : { ...this.formData }
        console.log('callStepTwo', this.formData)
        this.step = 2
        this.$nextTick(() => {
          if (
            !this.oldFormData ||
            this.oldFormData.startNodeId !== this.formData.startNodeId ||
            this.oldFormData.endNodeId !== this.formData.endNodeId ||
            this.oldFormData.cableId !== this.formData.cableId
          ) {
            this.$refs.StepTwo && this.$refs.StepTwo.refresh()
          }
        })
      },
      save() {
        console.log('this.formData', this.formData)
        if (
          this.formData.segmentChannelList.some(
            (i) =>
              i.startPortId === '' ||
              i.endPortId === '' ||
              (this.formData.cableId && i.fiberId === '')
          )
        ) {
          this.$message.error(this.$t('SELECT_ALL_CHANNEL'))
          return false
        }
        this.formData.cableId = this.formData.cableId || null
        this.formData.cableLength = this.formData.cableLength || null
        // 数据拼接(节点数据拼接)
        if (this.formData.segmentName.trim() === '') {
          this.$message.error(this.$t('MSG_NOT_EMPTY', {
            msg: this.$t('SEGMENT_NAME')
          }))
          return
        }
        this.modSegment()
      },
      modSegment() {
        // 差量提交数据
        const segmentChannelList = deepClone(this.formData.segmentChannelList)
        const addList = []
        const updateList = []
        const delList = this.oldChannelList.filter(
          (i) => !segmentChannelList.some((j) => j.channelId === i.channelId)
        )
        segmentChannelList.forEach((i, index) => {
          if (!i.channelId) {
            addList.push({
              sort: index + 1,
              segmentId: this.formData.segmentId,
              status: i.status,
              startNodeId: this.formData.startNodeId,
              startPortId: i.startPortId,
              startPortCategory: i.startPort.portCategory,
              fiberId: i.fiberId || null,
              endNodeId: this.formData.endNodeId,
              endPortId: i.endPortId,
              endPortCategory: i.endPort.portCategory
            })
          } else {
            const oldChannel = this.oldChannelList.find(
              (j) => j.channelId === i.channelId
            )
            const changedItem = {
              channelId: i.channelId
            }
            // 对比A端口有更改
            if (oldChannel.sort !== index + 1) {
              changedItem.sort = index + 1
            }
            // 对比A端口有更改
            if (oldChannel.startPortId !== i.startPortId) {
              changedItem.startPortId = i.startPortId
            }
            // 对比纤芯有更改
            if (oldChannel.fiberId !== i.fiberId) {
              changedItem.fiberId = i.fiberId
            }
            // 对比Z端口有更改
            if (oldChannel.endPortId !== i.endPortId) {
              changedItem.endPortId = i.endPortId
            }
            // 对比状态有更改
            if (oldChannel.status !== i.status) {
              changedItem.status = i.status
            }
            // 有数据更改就添加
            if (Object.keys(changedItem).length > 1) {
              updateList.push(changedItem)
            }
          }
        })
        const requestData = {
          networkSegmentId: this.formData.segmentId,
          addList: addList,
          updateList: updateList,
          delList: delList.map((i) => i.channelId),
          segmentName: this.formData.segmentName// 用于操作日志
        }
        if (this.rowData.segmentName !== this.formData.segmentName) {
          requestData.segmentName = this.formData.segmentName
        }
        console.log('requestData', requestData)
        segmentChannelApi.updateBySegmentId(requestData).then((res) => {
          this.$message.success(this.$t('MODIFY_SUCCESS'))
          this.close(true)
        })
      },
      close(load) {
        this.step = 1
        // 释放生成的select
        this.formData = { ...this.$options.data().formData }
        this.$emit('close', load)
      },
      resize() {
        this.$refs.StepTwo && this.$refs.StepTwo.selectBlur()
      }
    }
  }
</script>

<style scoped lang="scss">
  .segment-dialog {
    ::v-deep .el-dialog__body {
      position: relative;
      display: flex;
      flex-direction: column;
    }
  }
</style>
